/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.railway.app;

import com.railway.utils.CustomTableModel;
import com.railway.classes.Schedule;
import com.railway.utils.CustomScrollBarUI;
import com.railway.utils.RestServer;
import com.railway.utils.TextFieldLimiter;
import com.railway.utils.Toast;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.AbstractDocument;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *
 * @author Kenny
 */
public class TimetablePanel extends javax.swing.JPanel {

    Image imgArrow = new ImageIcon(this.getClass().getResource("/com/railway/image/arrow.png")).getImage();
    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    private ArrayList<String> colName;
    private ArrayList<ArrayList<Object>> rowData;
    private CustomTableModel ctmModel;
    private JSONObject json;
    private JSONArray jsonArray;
    private CardLayout cl;
    private Vector scheduleData;
    private DefaultComboBoxModel cbmSchedule;
    private String tableId = null;

    /**
     * Creates new form TimetablePanel
     */
    public TimetablePanel() {
        initComponents();
        cl = (CardLayout) jpTimetableCard.getLayout();
        getActiveSchedule(jcbxMSchedule);
    }

    public void populateTableData(final String sid) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                colName = new ArrayList<>();
                colName.add("Table ID");
                colName.add("UID");
                colName.add("shid");
                colName.add("Schedule Name");
                colName.add("Date");
                String result = RestServer.httpGet("timetables", jtfStaffID.getText());
                try {
                    json = new JSONObject(result);
                    boolean error = json.optBoolean("error");
                    if (!error) {
                        int statuscode = json.getInt("status");
                        if (statuscode == 200) {
                            rowData = new ArrayList<>();
                            jsonArray = json.getJSONArray("content");
                            for (int i = 0; i < jsonArray.length(); i++) {
                                ArrayList<Object> temp = new ArrayList<>();
                                temp.add(jsonArray.getJSONObject(i).get("tableId"));
                                temp.add(jsonArray.getJSONObject(i).get("uid"));
                                temp.add(jsonArray.getJSONObject(i).get("shid"));
                                temp.add(jsonArray.getJSONObject(i).getString("scheduleName"));
                                temp.add(jsonArray.getJSONObject(i).getString("scheduleDate"));
                                rowData.add(temp);
                            }
                            ctmModel = new CustomTableModel(colName, rowData);
                            jtbTimetable.setModel(ctmModel);
                            jtbTimetable.removeColumn(jtbTimetable.getColumnModel().getColumn(0));
                            jtbTimetable.removeColumn(jtbTimetable.getColumnModel().getColumn(0));
                            jtbTimetable.removeColumn(jtbTimetable.getColumnModel().getColumn(0));
                            jtfStaffID.setEnabled(false);
                        } else {
                            Toast.makeText(getParent(), "Staff not found.", Toast.LENGTH_SHORT).display();
                            jtbTimetable.setModel(new DefaultTableModel(new Object[][]{}, new Object[]{}));
                        }
                    } else {
                        Toast.makeText(getParent(), json.getString("message"), Toast.LENGTH_SHORT).display();
                    }
                } catch (JSONException ex) {
                    Logger.getLogger(TimetablePanel.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }).start();
    }

    private void getActiveSchedule(final javax.swing.JComboBox cbb) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                scheduleData = new Vector();
                String result = RestServer.httpGet("schedule/active", "");
                try {
                    json = new JSONObject(result);
                    boolean error = json.optBoolean("error");
                    if (!error) {
                        int statuscode = json.getInt("status");
                        if (statuscode == 200) {
                            jsonArray = json.getJSONArray("content");
                            for (int i = 0; i < jsonArray.length(); i++) {
                                Schedule route = new Schedule(jsonArray.getJSONObject(i).getInt("shid"), jsonArray.getJSONObject(i).getString("scheduleName"));
                                scheduleData.add(route);
                            }
                            cbmSchedule = new DefaultComboBoxModel(scheduleData);
                            cbb.setModel(cbmSchedule);
                        } else {
                            Toast.makeText(getParent(), "No active schedules found.", Toast.LENGTH_SHORT).display();
                        }
                    } else {
                        Toast.makeText(getParent(), "Error occured, please try again later.", Toast.LENGTH_SHORT).display();
                    }
                } catch (JSONException ex) {
                }
            }
        }).start();
    }

    private String buildJson(ArrayList<String> data) {
        JSONObject jsList;
        JSONArray jsListArr = new JSONArray();

        for (int i = 0; i < data.size(); i++) {
            jsList = new JSONObject();
            try {
                String string = data.get(i);
                jsListArr.put(jsList.put("date", string));
            } catch (JSONException ex) {
            }
        }
        return jsListArr.toString();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpTimetableArrow = new javax.swing.JPanel(){
            protected void paintComponent(Graphics g){
                super.paintComponent(g);
                g.drawImage(imgArrow, 0, 0, getWidth(), imgArrow.getHeight(this), this);
            }
        };
        jpTimetableContent = new javax.swing.JPanel();
        jlblStaffTimetable = new javax.swing.JLabel();
        jsprTimetable = new javax.swing.JSeparator();
        jspTimetableScroller = new javax.swing.JScrollPane();
        jtbTimetable = new javax.swing.JTable();
        jlblStaffID = new javax.swing.JLabel();
        jtfStaffID = new javax.swing.JTextField();
        jbtSearch = new javax.swing.JButton();
        jpTimetable = new javax.swing.JPanel();
        jbtAddTimetable = new javax.swing.JButton();
        jbtModifyTimetable = new javax.swing.JButton();
        jpTimetableCard = new javax.swing.JPanel();
        jpNullCard = new javax.swing.JPanel();
        jpAddCard = new javax.swing.JPanel();
        jpAddTimetableArrow = new javax.swing.JPanel(){
            protected void paintComponent(Graphics g){
                super.paintComponent(g);
                g.drawImage(imgArrow, 0, 0, getWidth(), imgArrow.getHeight(this), this);
            }
        };
        jpAddTimetable = new javax.swing.JPanel();
        jlblAStaff = new javax.swing.JLabel();
        jtfAStaff = new javax.swing.JTextField();
        jbtSearchStaff = new javax.swing.JButton();
        jlbASchedule = new javax.swing.JLabel();
        jcbxASchedule = new javax.swing.JComboBox();
        jlblADateFrom = new javax.swing.JLabel();
        jdcFrom = new com.toedter.calendar.JDateChooser();
        jlblTo = new javax.swing.JLabel();
        jdcTo = new com.toedter.calendar.JDateChooser();
        jbtReset = new javax.swing.JButton();
        jbtASubmit = new javax.swing.JButton();
        jpModifyCard = new javax.swing.JPanel();
        jpModifyTimetableArrow = new javax.swing.JPanel(){
            protected void paintComponent(Graphics g){
                super.paintComponent(g);
                g.drawImage(imgArrow, 0, 0, getWidth(), imgArrow.getHeight(this), this);
            }
        };
        jpModifyTimetable = new javax.swing.JPanel();
        jlblMStaff = new javax.swing.JLabel();
        jtfMStaff = new javax.swing.JTextField();
        jcbxMSchedule = new javax.swing.JComboBox();
        jlblMSchedule = new javax.swing.JLabel();
        jlblScheduleDate = new javax.swing.JLabel();
        jdcScheduleDate = new com.toedter.calendar.JDateChooser();
        jbtMSubmit = new javax.swing.JButton();
        jbtRemove = new javax.swing.JButton();

        setBackground(new java.awt.Color(255, 255, 255));
        setPreferredSize(new java.awt.Dimension(860, 375));
        setLayout(null);

        jpTimetableArrow.setBackground(new java.awt.Color(255, 255, 255));

        javax.swing.GroupLayout jpTimetableArrowLayout = new javax.swing.GroupLayout(jpTimetableArrow);
        jpTimetableArrow.setLayout(jpTimetableArrowLayout);
        jpTimetableArrowLayout.setHorizontalGroup(
            jpTimetableArrowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 180, Short.MAX_VALUE)
        );
        jpTimetableArrowLayout.setVerticalGroup(
            jpTimetableArrowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 10, Short.MAX_VALUE)
        );

        add(jpTimetableArrow);
        jpTimetableArrow.setBounds(450, 0, 180, 10);

        jpTimetableContent.setBackground(new java.awt.Color(255, 255, 255));
        jpTimetableContent.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(220, 220, 220), 2));
        jpTimetableContent.setLayout(null);

        jlblStaffTimetable.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jlblStaffTimetable.setText("STAFF'S TIMETABLE");
        jpTimetableContent.add(jlblStaffTimetable);
        jlblStaffTimetable.setBounds(565, 0, 280, 20);
        jpTimetableContent.add(jsprTimetable);
        jsprTimetable.setBounds(565, 20, 280, 5);

        jspTimetableScroller.getVerticalScrollBar().setUI(new CustomScrollBarUI());

        jtbTimetable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jspTimetableScroller.setViewportView(jtbTimetable);

        jpTimetableContent.add(jspTimetableScroller);
        jspTimetableScroller.setBounds(565, 50, 280, 305);

        jlblStaffID.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jlblStaffID.setText("Enter staff' s ID");
        jpTimetableContent.add(jlblStaffID);
        jlblStaffID.setBounds(565, 25, 90, 20);

        AbstractDocument docStaffId = (AbstractDocument)jtfStaffID.getDocument();
        docStaffId.setDocumentFilter(new TextFieldLimiter("\\d{0,}"));
        jtfStaffID.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jpTimetableContent.add(jtfStaffID);
        jtfStaffID.setBounds(655, 25, 110, 20);

        jbtSearch.setBackground(new java.awt.Color(39, 174, 96));
        jbtSearch.setFont(new java.awt.Font("Segoe UI Emoji", 0, 14)); // NOI18N
        jbtSearch.setForeground(new java.awt.Color(255, 255, 255));
        jbtSearch.setText("Search");
        jbtSearch.setFocusPainted(false);
        jbtSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtSearchActionPerformed(evt);
            }
        });
        jpTimetableContent.add(jbtSearch);
        jbtSearch.setBounds(770, 25, 75, 20);

        jpTimetable.setBackground(new java.awt.Color(255, 255, 255));
        jpTimetable.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(220, 220, 220), 2));
        jpTimetable.setLayout(null);

        jbtAddTimetable.setBackground(new java.awt.Color(155, 89, 182));
        jbtAddTimetable.setFont(new java.awt.Font("Segoe UI Emoji", 0, 14)); // NOI18N
        jbtAddTimetable.setForeground(new java.awt.Color(255, 255, 255));
        jbtAddTimetable.setText("Add Timetable");
        jbtAddTimetable.setFocusPainted(false);
        jbtAddTimetable.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtAddTimetableActionPerformed(evt);
            }
        });
        jpTimetable.add(jbtAddTimetable);
        jbtAddTimetable.setBounds(5, 5, 200, 50);

        jbtModifyTimetable.setBackground(new java.awt.Color(155, 89, 182));
        jbtModifyTimetable.setFont(new java.awt.Font("Segoe UI Emoji", 0, 14)); // NOI18N
        jbtModifyTimetable.setForeground(new java.awt.Color(255, 255, 255));
        jbtModifyTimetable.setText("Modify Timetable");
        jbtModifyTimetable.setFocusPainted(false);
        jbtModifyTimetable.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtModifyTimetableActionPerformed(evt);
            }
        });
        jpTimetable.add(jbtModifyTimetable);
        jbtModifyTimetable.setBounds(345, 5, 200, 50);

        jpTimetableCard.setBackground(new java.awt.Color(255, 255, 255));
        jpTimetableCard.setLayout(new java.awt.CardLayout());

        jpNullCard.setBackground(new java.awt.Color(255, 255, 255));

        javax.swing.GroupLayout jpNullCardLayout = new javax.swing.GroupLayout(jpNullCard);
        jpNullCard.setLayout(jpNullCardLayout);
        jpNullCardLayout.setHorizontalGroup(
            jpNullCardLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 540, Short.MAX_VALUE)
        );
        jpNullCardLayout.setVerticalGroup(
            jpNullCardLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 290, Short.MAX_VALUE)
        );

        jpTimetableCard.add(jpNullCard, "null");

        jpAddCard.setBackground(new java.awt.Color(255, 255, 255));
        jpAddCard.setLayout(null);

        jpAddTimetableArrow.setBackground(new java.awt.Color(255, 255, 255));

        javax.swing.GroupLayout jpAddTimetableArrowLayout = new javax.swing.GroupLayout(jpAddTimetableArrow);
        jpAddTimetableArrow.setLayout(jpAddTimetableArrowLayout);
        jpAddTimetableArrowLayout.setHorizontalGroup(
            jpAddTimetableArrowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 200, Short.MAX_VALUE)
        );
        jpAddTimetableArrowLayout.setVerticalGroup(
            jpAddTimetableArrowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 10, Short.MAX_VALUE)
        );

        jpAddCard.add(jpAddTimetableArrow);
        jpAddTimetableArrow.setBounds(0, 0, 200, 10);

        jpAddTimetable.setBackground(new java.awt.Color(255, 255, 255));
        jpAddTimetable.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(220, 220, 220), 2));
        jpAddTimetable.setLayout(null);

        jlblAStaff.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jlblAStaff.setText("Staff ID");
        jpAddTimetable.add(jlblAStaff);
        jlblAStaff.setBounds(10, 10, 120, 30);

        AbstractDocument docStaff = (AbstractDocument)jtfAStaff.getDocument();
        docStaff.setDocumentFilter(new TextFieldLimiter("\\d{0,}"));
        jtfAStaff.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jpAddTimetable.add(jtfAStaff);
        jtfAStaff.setBounds(130, 10, 170, 30);

        jbtSearchStaff.setBackground(new java.awt.Color(39, 174, 96));
        jbtSearchStaff.setFont(new java.awt.Font("Segoe UI Emoji", 0, 14)); // NOI18N
        jbtSearchStaff.setForeground(new java.awt.Color(255, 255, 255));
        jbtSearchStaff.setText("Search");
        jbtSearchStaff.setFocusPainted(false);
        jbtSearchStaff.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtSearchStaffActionPerformed(evt);
            }
        });
        jpAddTimetable.add(jbtSearchStaff);
        jbtSearchStaff.setBounds(310, 10, 90, 30);

        jlbASchedule.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jlbASchedule.setText("Choose Schedule");
        jpAddTimetable.add(jlbASchedule);
        jlbASchedule.setBounds(10, 60, 120, 30);

        jcbxASchedule.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jcbxASchedule.setEnabled(false);
        jpAddTimetable.add(jcbxASchedule);
        jcbxASchedule.setBounds(130, 60, 170, 30);

        jlblADateFrom.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jlblADateFrom.setText("Date From");
        jpAddTimetable.add(jlblADateFrom);
        jlblADateFrom.setBounds(10, 110, 120, 30);

        jdcFrom.setEnabled(false);
        jdcFrom.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jdcFrom.setMinSelectableDate(new java.util.Date());
        jpAddTimetable.add(jdcFrom);
        jdcFrom.setBounds(130, 110, 170, 30);

        jlblTo.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jlblTo.setText("to");
        jpAddTimetable.add(jlblTo);
        jlblTo.setBounds(310, 110, 20, 30);

        jdcTo.setEnabled(false);
        jdcTo.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jdcTo.setMinSelectableDate(new java.util.Date());
        jpAddTimetable.add(jdcTo);
        jdcTo.setBounds(330, 110, 170, 30);

        jbtReset.setBackground(new java.awt.Color(39, 174, 96));
        jbtReset.setFont(new java.awt.Font("Segoe UI Emoji", 0, 14)); // NOI18N
        jbtReset.setForeground(new java.awt.Color(255, 255, 255));
        jbtReset.setText("Reset");
        jbtReset.setFocusPainted(false);
        jbtReset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtResetActionPerformed(evt);
            }
        });
        jpAddTimetable.add(jbtReset);
        jbtReset.setBounds(10, 200, 150, 50);

        jbtASubmit.setBackground(new java.awt.Color(39, 174, 96));
        jbtASubmit.setFont(new java.awt.Font("Segoe UI Emoji", 0, 14)); // NOI18N
        jbtASubmit.setForeground(new java.awt.Color(255, 255, 255));
        jbtASubmit.setText("Submit");
        jbtASubmit.setFocusPainted(false);
        jbtASubmit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtASubmitActionPerformed(evt);
            }
        });
        jpAddTimetable.add(jbtASubmit);
        jbtASubmit.setBounds(360, 200, 150, 50);

        jpAddCard.add(jpAddTimetable);
        jpAddTimetable.setBounds(0, 10, 540, 280);

        jpTimetableCard.add(jpAddCard, "addcard");

        jpModifyCard.setBackground(new java.awt.Color(255, 255, 255));
        jpModifyCard.setLayout(null);

        jpModifyTimetableArrow.setBackground(new java.awt.Color(255, 255, 255));

        javax.swing.GroupLayout jpModifyTimetableArrowLayout = new javax.swing.GroupLayout(jpModifyTimetableArrow);
        jpModifyTimetableArrow.setLayout(jpModifyTimetableArrowLayout);
        jpModifyTimetableArrowLayout.setHorizontalGroup(
            jpModifyTimetableArrowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 200, Short.MAX_VALUE)
        );
        jpModifyTimetableArrowLayout.setVerticalGroup(
            jpModifyTimetableArrowLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 10, Short.MAX_VALUE)
        );

        jpModifyCard.add(jpModifyTimetableArrow);
        jpModifyTimetableArrow.setBounds(340, 0, 200, 10);

        jpModifyTimetable.setBackground(new java.awt.Color(255, 255, 255));
        jpModifyTimetable.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(220, 220, 220), 2));
        jpModifyTimetable.setLayout(null);

        jlblMStaff.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jlblMStaff.setText("Staff ID");
        jpModifyTimetable.add(jlblMStaff);
        jlblMStaff.setBounds(10, 10, 120, 30);

        AbstractDocument docMStaff = (AbstractDocument)jtfMStaff.getDocument();
        docMStaff.setDocumentFilter(new TextFieldLimiter("\\d{0,}"));
        jtfMStaff.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jpModifyTimetable.add(jtfMStaff);
        jtfMStaff.setBounds(130, 10, 170, 30);

        jpModifyTimetable.add(jcbxMSchedule);
        jcbxMSchedule.setBounds(130, 60, 170, 30);

        jlblMSchedule.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jlblMSchedule.setText("Schedule");
        jpModifyTimetable.add(jlblMSchedule);
        jlblMSchedule.setBounds(10, 60, 120, 30);

        jlblScheduleDate.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jlblScheduleDate.setText("Schedule Date");
        jpModifyTimetable.add(jlblScheduleDate);
        jlblScheduleDate.setBounds(10, 110, 120, 30);

        jdcScheduleDate.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jdcScheduleDate.setMinSelectableDate(new Date());
        jpModifyTimetable.add(jdcScheduleDate);
        jdcScheduleDate.setBounds(130, 110, 170, 30);

        jbtMSubmit.setBackground(new java.awt.Color(39, 174, 96));
        jbtMSubmit.setFont(new java.awt.Font("Segoe UI Emoji", 0, 14)); // NOI18N
        jbtMSubmit.setForeground(new java.awt.Color(255, 255, 255));
        jbtMSubmit.setText("Submit");
        jbtMSubmit.setFocusPainted(false);
        jbtMSubmit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtMSubmitActionPerformed(evt);
            }
        });
        jpModifyTimetable.add(jbtMSubmit);
        jbtMSubmit.setBounds(360, 200, 150, 50);

        jbtRemove.setBackground(new java.awt.Color(39, 174, 96));
        jbtRemove.setFont(new java.awt.Font("Segoe UI Emoji", 0, 14)); // NOI18N
        jbtRemove.setForeground(new java.awt.Color(255, 255, 255));
        jbtRemove.setText("Remove");
        jbtRemove.setFocusPainted(false);
        jbtRemove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtRemoveActionPerformed(evt);
            }
        });
        jpModifyTimetable.add(jbtRemove);
        jbtRemove.setBounds(10, 200, 150, 50);

        jpModifyCard.add(jpModifyTimetable);
        jpModifyTimetable.setBounds(0, 10, 540, 280);

        jpTimetableCard.add(jpModifyCard, "modifycard");

        jpTimetable.add(jpTimetableCard);
        jpTimetableCard.setBounds(5, 55, 540, 290);

        jpTimetableContent.add(jpTimetable);
        jpTimetable.setBounds(5, 5, 550, 350);

        add(jpTimetableContent);
        jpTimetableContent.setBounds(5, 10, 850, 360);
    }// </editor-fold>//GEN-END:initComponents

    private void jbtSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtSearchActionPerformed
        if (jtfStaffID.isEnabled()) {
            populateTableData(jtfStaffID.getText());
        } else {
            jtfStaffID.setEnabled(true);
        }
    }//GEN-LAST:event_jbtSearchActionPerformed

    private void jbtAddTimetableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtAddTimetableActionPerformed
        jbtAddTimetable.setBackground(new Color(142, 68, 173));
        jbtModifyTimetable.setBackground(new Color(155, 89, 182));
        cl.show(jpTimetableCard, "addcard");
    }//GEN-LAST:event_jbtAddTimetableActionPerformed

    private void jbtModifyTimetableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtModifyTimetableActionPerformed
        jbtAddTimetable.setBackground(new Color(155, 89, 182));
        jbtModifyTimetable.setBackground(new Color(142, 68, 173));
        if (jtbTimetable.getSelectedRow() >= 0) {
            cl.show(jpTimetableCard, "modifycard");
            tableId = jtbTimetable.getModel().getValueAt(jtbTimetable.getSelectedRow(), 0).toString();
            jtfMStaff.setText(jtbTimetable.getModel().getValueAt(jtbTimetable.getSelectedRow(), 1).toString());
            Schedule selectedSchedule = new Schedule(
                    Integer.parseInt(
                    jtbTimetable.getModel().getValueAt(
                    jtbTimetable.getSelectedRow(), 2).toString()), jtbTimetable.getValueAt(
                    jtbTimetable.getSelectedRow(), 0).toString());
            jcbxMSchedule.setSelectedItem(selectedSchedule);
            Date date = null;
            try {
                date = format.parse(jtbTimetable.getValueAt(jtbTimetable.getSelectedRow(), 1).toString());
            } catch (ParseException ex) {
            }
            jdcScheduleDate.setDate(date);

        } else {
            Toast.makeText(this, "Please make selection from table first.", Toast.LENGTH_SHORT).display();
        }
    }//GEN-LAST:event_jbtModifyTimetableActionPerformed

    private void jbtSearchStaffActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtSearchStaffActionPerformed
        if (!jtfAStaff.getText().equals("")) {
            String result = RestServer.httpGet("staff", jtfAStaff.getText());
            try {
                json = new JSONObject(result);
                boolean error = json.optBoolean("error");
                if (!error) {
                    int statuscode = json.getInt("status");
                    if (statuscode == 200) {
                        Toast.makeText(this, "Staff found, please proceed to add timetable.", Toast.LENGTH_SHORT).display();
                        jcbxASchedule.setEnabled(true);
                        jdcFrom.setEnabled(true);
                        jdcTo.setEnabled(true);
                        getActiveSchedule(jcbxASchedule);
                    } else {
                        Toast.makeText(this, "Staff not found.", Toast.LENGTH_SHORT).display();
                        jcbxASchedule.setEnabled(false);
                        jdcFrom.setEnabled(false);
                        jdcTo.setEnabled(false);
                    }
                } else {
                    Toast.makeText(this, json.getString("message"), Toast.LENGTH_SHORT).display();
                }
            } catch (JSONException ex) {
            }
        } else {
            Toast.makeText(this, "Please fill in staff ID first.", Toast.LENGTH_SHORT).display();
        }

    }//GEN-LAST:event_jbtSearchStaffActionPerformed

    private void jbtASubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtASubmitActionPerformed
        if (!jtfAStaff.getText().equals("") && jdcFrom.getDate() != null && jdcTo.getDate() != null) {
            ArrayList<String> timeRange = new ArrayList<>();
            Calendar start = Calendar.getInstance();
            start.setTime(jdcFrom.getDate());
            Calendar end = Calendar.getInstance();
            end.setTime(jdcTo.getDate());
            Date temp = new Date();
            for (start.getTime(); !start.after(end); start.add(Calendar.DATE, 1)) {
                temp.setTime(start.getTimeInMillis());
                timeRange.add(format.format(temp));
            }
            Map<String, Object> data = new HashMap<>();
            data.put("shid", ((Schedule) jcbxASchedule.getSelectedItem()).getShid());
            data.put("dates", buildJson(timeRange));
            String result = RestServer.httpPost("timetables/" + jtfAStaff.getText(), data);
            try {
                json = new JSONObject(result);
                boolean error = json.optBoolean("error");
                if (!error) {
                    int statuscode = json.getInt("status");
                    if (statuscode == 200) {
                        Toast.makeText(this, "Timetable added successfully.", Toast.LENGTH_SHORT).display();
                    } else {
                        Toast.makeText(this, "Unable to create new timetable now, please try again later.", Toast.LENGTH_SHORT).display();
                    }
                } else {
                    Toast.makeText(this, json.getString("message"), Toast.LENGTH_SHORT).display();
                }
            } catch (JSONException ex) {
            }
        } else {
            Toast.makeText(this, "Please fill in all fields first.", Toast.LENGTH_SHORT).display();
        }
    }//GEN-LAST:event_jbtASubmitActionPerformed

    private void jbtResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtResetActionPerformed
        jtfAStaff.setText(null);
        jcbxASchedule.setSelectedIndex(0);
        jdcFrom.setDate(null);
        jdcTo.setDate(null);
    }//GEN-LAST:event_jbtResetActionPerformed

    private void jbtRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtRemoveActionPerformed
        int option = JOptionPane.showConfirmDialog(this, "Are you sure you want to remove this schedule?", "Confirmation", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if (option == JOptionPane.YES_OPTION) {
            String result = RestServer.httpDelete("timetable", tableId);
            try {
                json = new JSONObject(result);
                boolean error = json.optBoolean("error");
                if (!error) {
                    int statuscode = json.getInt("status");
                    if (statuscode == 200) {
                        Toast.makeText(this, "Schedule has beed removed.", Toast.LENGTH_SHORT).display();
                        cl.show(jpTimetableCard, "null");
                        populateTableData(jtfStaffID.getText());
                    } else {
                        Toast.makeText(this, "Unable to remove now, please try again later", Toast.LENGTH_SHORT).display();
                    }
                } else {
                    Toast.makeText(this, json.getString("message"), Toast.LENGTH_SHORT).display();
                }
            } catch (JSONException ex) {
            }
        }
    }//GEN-LAST:event_jbtRemoveActionPerformed

    private void jbtMSubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtMSubmitActionPerformed
        Map<String, Object> data = new HashMap<>();
        data.put("uid", jtfMStaff.getText());
        data.put("shid", ((Schedule)jcbxMSchedule.getSelectedItem()).getShid());
        data.put("date", format.format(jdcScheduleDate.getDate()));
        String result = RestServer.httpPut(
                "timetable", data, jtbTimetable.getModel().getValueAt(jtbTimetable.getSelectedRow(), 0).toString());
        try {
            json = new JSONObject(result);
            boolean error = json.optBoolean("error");
            if (!error) {
                int statuscode = json.getInt("status");
                if (statuscode == 200) {
                    Toast.makeText(this, "Schedule has beed updated.", Toast.LENGTH_SHORT).display();
                    cl.show(jpTimetableCard, "null");
                    populateTableData(jtfStaffID.getText());
                } else {
                    Toast.makeText(this, "Unable to update now, please try again later", Toast.LENGTH_SHORT).display();
                }
            } else {
                Toast.makeText(this, json.getString("message"), Toast.LENGTH_SHORT).display();
            }
        } catch (JSONException ex) {
        }

    }//GEN-LAST:event_jbtMSubmitActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jbtASubmit;
    private javax.swing.JButton jbtAddTimetable;
    private javax.swing.JButton jbtMSubmit;
    private javax.swing.JButton jbtModifyTimetable;
    private javax.swing.JButton jbtRemove;
    private javax.swing.JButton jbtReset;
    private javax.swing.JButton jbtSearch;
    private javax.swing.JButton jbtSearchStaff;
    private javax.swing.JComboBox jcbxASchedule;
    private javax.swing.JComboBox jcbxMSchedule;
    private com.toedter.calendar.JDateChooser jdcFrom;
    private com.toedter.calendar.JDateChooser jdcScheduleDate;
    private com.toedter.calendar.JDateChooser jdcTo;
    private javax.swing.JLabel jlbASchedule;
    private javax.swing.JLabel jlblADateFrom;
    private javax.swing.JLabel jlblAStaff;
    private javax.swing.JLabel jlblMSchedule;
    private javax.swing.JLabel jlblMStaff;
    private javax.swing.JLabel jlblScheduleDate;
    private javax.swing.JLabel jlblStaffID;
    private javax.swing.JLabel jlblStaffTimetable;
    private javax.swing.JLabel jlblTo;
    private javax.swing.JPanel jpAddCard;
    private javax.swing.JPanel jpAddTimetable;
    private javax.swing.JPanel jpAddTimetableArrow;
    private javax.swing.JPanel jpModifyCard;
    private javax.swing.JPanel jpModifyTimetable;
    private javax.swing.JPanel jpModifyTimetableArrow;
    private javax.swing.JPanel jpNullCard;
    private javax.swing.JPanel jpTimetable;
    private javax.swing.JPanel jpTimetableArrow;
    private javax.swing.JPanel jpTimetableCard;
    private javax.swing.JPanel jpTimetableContent;
    private javax.swing.JScrollPane jspTimetableScroller;
    private javax.swing.JSeparator jsprTimetable;
    private javax.swing.JTable jtbTimetable;
    private javax.swing.JTextField jtfAStaff;
    private javax.swing.JTextField jtfMStaff;
    private javax.swing.JTextField jtfStaffID;
    // End of variables declaration//GEN-END:variables
}
